#-*- coding: utf-8 -*-
from pandac.PandaModules import *
from pmcore.basecom import BaseComponent

class SampleModelLoader(BaseComponent):
    name = "Sample model loader"
    weight = 11
    version = "0.1"
    author = "Ninth"
    requires = "menu-control"
    scene = NodePath("SceneRoot")
    mpath = []
    
    def after_direct_import(self):
        self.scene.reparentTo(render)
        mnuctrl = get_service("menu-control")
        mnuctrl.add_menu_item("File->Load model...",self.onMClick)
        mnuctrl.add_menu_item("File->Save model...",self.onMClick2)
        
    def onMClick(self,*args, **kwargs):
        fdlg = get_service("file-dialog")
        fdlg.wildcard = "All files (*.*)|*.*|"\
            "Models (*.egg)|*.egg|"\
            "Packed models (*.pz)|*.pz|"\
            "Compiled models (*.bam)|*.bam"
        flist = fdlg.open()
        if flist:
            self.load_model(flist)

    def onMClick2(self,*args, **kwargs):
        fdlg = get_service("file-dialog")
        fdlg.wildcard = "Compiled models (*.bam)|*.bam"
        flist = fdlg.open(dtype = "Save")
        if flist:
            self.save_model(flist)
        
    def load_model(self,paths):
        send_event("model-loader-before-load")
        messenger.send("model-loader-before-load")
        self.scene.removeNode()
        if self.mpath:
            for p in self.mpath:
                loader.unloadModel(p)
                
        self.scene = NodePath("SceneRoot")
        self.scene.reparentTo(render)
        self.mpath = []
        for fn in paths:
            print "Sample model loader: LOAD ",fn
            mdl = loader.loadModel(Filename.fromOsSpecific(fn))
            mdl.reparentTo(self.scene)
            self.mpath.append(fn)
        #self.scene.flattenLight()
        self.scene.analyze()
        sreset = get_service("npselector-reset-scene")
        if sreset:
            sreset(self.scene)
        scsp = get_service("strategy-camera-set-parametres")
        if scsp:
            pt1,pt2 = self.scene.getTightBounds()
            #print "BB", pt1,pt2
            size = 0
            for i in xrange(3):
                if abs(pt2[i]-pt1[i]) > size: 
                    size = abs(pt2[i]-pt1[i])            
            scsp(distance = size*4)
        send_event("model-loader-after-load")
        messenger.send("model-loader-after-load")
        
    def save_model(self,fname):
        #print "SAVE: to %s" % fname
        if fname:
            send_event("model-loader-before-save")
            messenger.send("model-loader-before-save")
            fn = fname[0]
            if len(self.scene.getChildren())>1:
                self.scene.writeBamFile(Filename.fromOsSpecific(fn).cStr())
            elif len(self.scene.getChildren()) == 1:
                self.scene.getChildren()[0].writeBamFile(Filename.fromOsSpecific(fn).cStr())
            send_event("model-loader-after-save")
            messenger.send("model-loader-after-save")
            
